﻿using SUNRPA.CONTROLS.IMPL.domain;
using SUNRPA.CONTROLS.IMPL.domain.constant;
using SUNRPA.CONTROLS.IMPL.domain.flowItemParam;
using SUNRPA.CONTROLS.IMPL.domain.flowRunningVar;
using SUNRPA.CONTROLS.IMPL.util;
using System.Collections;
using System.Collections.Concurrent;

namespace SUNRPA.CONTROLS.IMPL.controls {
    public class ForEachNAction:BaseControlActions {
        public override int Execute(int currentIndex, FlowItem item, ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>> globleData, List<FlowItem> flowItems) {
            ForEachNParam? param = item.ControlParam as ForEachNParam;
            string listName = param.ListName;
            List<object> runTimeVar = this.GetObjVar<List<object>>(ref listName, globleData);
            if(runTimeVar == null) { 
                throw new RpaRuntimeException(string.Format("列表变量{0}不存在", listName));
            }

            string start = param.StartIndex;
            string end = param.EndIndex;
            this.GetStringVar(ref start, globleData);
            this.GetStringVar(ref end, globleData);
            int startI = int.Parse(start);
            int endI = int.Parse(end);

            int startIndex = (startI >= runTimeVar.Count || startI < 0) ? 0 : startI;
            int endIndex = (endI <= 0 || endI > runTimeVar.Count)  ? runTimeVar.Count : endI;
           
            string loopItemName = param.LoopItemName;
            string loopIndexName = param.LoopIndexName;
            for(int i = startIndex; i < endIndex; i++) { 
                this.saveVar(globleData, loopItemName, new OtherModel(loopItemName, runTimeVar[i]), DefaultContents.RUNNING_PARAM);
                this.saveVar(globleData, loopIndexName, new IntModel(loopIndexName, i), DefaultContents.RUNNING_PARAM);
                //顺序执行定义在循环中的流程项
                for(int j = currentIndex + 1; j < item.EndTag.Index; j++) {
                    BaseControlActions.updateInfoDelegate(j);
                    j = ExecuteAction(flowItems[j], globleData, flowItems);
                }
            }
            return item.EndTag.Index;
        }
    }
}
